package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * Created by zwj on 2017/10/15.
 * 我的钱包
 */

public class MineWalletFragment extends BaseFragment implements View.OnClickListener {

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;

    //左标提
    private TextView topbar_textview_leftitle;
    //标题
    private TextView topbar_textview_title;

    //钱包余额
    private TextView wallet_balance_text;
    private String walletBalanceStr;
    //总资产
    private TextView wallet_balance_all_text;
    private String walletBalanceAllStr;
    //预计收入
    private TextView wallet_expect_text;
    private String walletExpectStr;
    //用户注册时间
    private String dt_register;
    //我的银行卡
    private LinearLayout mine_card_text;
    //提现
    private ImageView extract_money_image;


    //所有布局
    private LinearLayout all_linear;

    //正在审核
    private LinearLayout zhengzaishenhe_linear;
    private TextView zhengzaishenhe_text;

    //认证失败
    private LinearLayout renzhengshibai_linear;
    private TextView submit_text;

    private FormalUserInfo userInfo;

    //审核状态
    private String kyc_status;
    //钱包状态
    private String stat_user;

    //判断身份  1个人   2企业
    private int isUse = 1;
    //是否是企业钱包--有值是企业  空是个人
    private String type_register;

    //用户所属商户号
    private String oid_partner;
    //证件号码
    private String no_idcard;
    //姓名
    private String name_user;

    private int userid;

    private SharedPreferanceUtils mSharePreferanceUtils = null;

    public static MineWalletFragment newInstance() {

        Bundle args = new Bundle();
        MineWalletFragment fragment = new MineWalletFragment();
//        args.putSerializable("userInfo", userInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_minewallet, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListener();
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        userid = userInfo.getId();
        IsWalletUser(String.valueOf(userid), "RSA");

    }

    private void initView(View view) {
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("可提现金额");
        wallet_balance_text = (TextView) view.findViewById(R.id.wallet_balance_text);
        wallet_balance_all_text = (TextView) view.findViewById(R.id.wallet_balance_all_text);
        mine_card_text = (LinearLayout) view.findViewById(R.id.mine_card_text);
        extract_money_image = (ImageView) view.findViewById(R.id.extract_money_image);
        all_linear = (LinearLayout) view.findViewById(R.id.all_linear);
        zhengzaishenhe_linear = (LinearLayout) view.findViewById(R.id.zhengzaishenhe_linear);
        zhengzaishenhe_text = (TextView) view.findViewById(R.id.zhengzaishenhe_text);
        renzhengshibai_linear = (LinearLayout) view.findViewById(R.id.renzhengshibai_linear);
        submit_text = (TextView) view.findViewById(R.id.submit_text);
        submit_text.setOnClickListener(this);
        wallet_expect_text = (TextView) view.findViewById(R.id.wallet_expect_text);
        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
    }

    private void initListener() {
        topbar_textview_leftitle.setOnClickListener(this);
        mine_card_text.setOnClickListener(this);
        extract_money_image.setOnClickListener(this);
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
    }

    /**
     * 判断身份
     */
    private void judgmentIdentity() {
                //个人身份
                isUse = 1;
                mine_card_text.setVisibility(View.VISIBLE);
    }

    //是否是钱包用户
    public void IsWalletUser(final String user_id, String sign_type) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("sign_type", sign_type);

//        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("user_id", user_id);
        paramMaps.put("sign_type", sign_type);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.IS_WALLET_USER, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
//                    LogUtils.e("content_判断是否钱包用户", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject singleuserquery = jsonObject.optJSONObject("singleuserquery");
                        String ret_code = singleuserquery.optString("ret_code");
                        kyc_status = singleuserquery.optString("kyc_status");
                        stat_user = singleuserquery.optString("stat_user");
                        walletBalanceStr = jsonObject.optString("balance");
                        walletBalanceAllStr = jsonObject.optString("sum");
                        walletExpectStr = jsonObject.optString("income");
                        dt_register = singleuserquery.optString("dt_register");
                        oid_partner = singleuserquery.optString("oid_partner");
                        no_idcard = singleuserquery.optString("no_idcard");
                        name_user = singleuserquery.optString("name_user");
                        type_register = singleuserquery.optString("type_register");
                        judgmentIdentity();
                        if ("0000".equals(ret_code)) {
                            if ("1".equals(kyc_status) ||"4".equals(kyc_status) || "2".equals(stat_user)|| "1".equals(stat_user)) {
                                all_linear.setVisibility(View.VISIBLE);
                                wallet_balance_text.setText(walletBalanceStr);
                                wallet_balance_all_text.setText(walletBalanceAllStr);
                                wallet_expect_text.setText(walletExpectStr);
                                if (walletBalanceStr.equals("0.00")) {
//                                    extract_money_text.setBackgroundColor(getResources().getColor(R.color.gray_view));
                                    extract_money_image.setEnabled(false);

                                } else {
//                                    extract_money_text.setBackgroundColor(getResources().getColor(R.color.apply_ing_color));
                                    extract_money_image.setEnabled(true);
                                }
                            } else if ("3".equals(kyc_status)) {
                                all_linear.setVisibility(View.GONE);
                                zhengzaishenhe_linear.setVisibility(View.VISIBLE);
                                zhengzaishenhe_text.setText(String.format(getResources().getString(R.string.wallet_zhengzaishenhe), dt_register));
                            } else {
                                all_linear.setVisibility(View.GONE);
                                zhengzaishenhe_linear.setVisibility(View.GONE);
                                renzhengshibai_linear.setVisibility(View.VISIBLE);
                            }

                        } else {
                            all_linear.setVisibility(View.GONE);
                            showDialog();
                        }
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }


    /**
     * 没有钱包账户 开通账户
     */
    private void showDialog() {
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final LinearLayout dialogView = (LinearLayout) factory.inflate(
                R.layout.dialog_two_textview, null);

        //开通企业钱包
        final TextView open_wallet_text = (TextView) dialogView.findViewById(R.id.open_wallet_text);
        //开通个人钱包
        final TextView open_wallet_personal_text = (TextView) dialogView.findViewById(R.id.open_wallet_personal_text);

        // 对话框
        final Dialog dialog = new Dialog(getActivity(), R.style.MyDialogStyle);

        if (isUse == 2) {
            open_wallet_text.setVisibility(View.VISIBLE);
        } else {
            open_wallet_text.setVisibility(View.GONE);
        }

        //点击区域外消除
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.getWindow().setContentView(dialogView);
        //开通企业钱包
        open_wallet_text.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                type_register = "2";
                startForResult(OpenWalletFragment.newInstance(type_register, userInfo, oid_partner, stat_user, name_user, no_idcard, 1), 1);
                dialog.dismiss();
            }
        });

        //开通个人钱包
        open_wallet_personal_text.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                type_register = "";
                startForResult(OpenWalletFragment.newInstance(type_register, userInfo, oid_partner, stat_user, name_user, no_idcard, 1), 1);
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    IsWalletUser(userInfo.getId() + "", "RSA");
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.mine_card_text:
                //我的银行卡
                startForResult(ExtractMoneyBankFragment.newInstance(userInfo, walletBalanceStr, oid_partner), 1);
                break;
            case R.id.extract_money_image:
                //提现
                if (isUse == 1 && "null".equals(type_register)) {
                    startForResult(ExtractMoneyBankFragment.newInstance(userInfo, walletBalanceStr, oid_partner), 1);
                } else {
                    if (kyc_status.equals("3")) {
                        showShortToast("您的信息正在审核中");
                    } else if (kyc_status.equals("4")) {
                        startForResult(ExtractMoneyEnterpriseFragment.newInstance(userInfo, walletBalanceStr, oid_partner), 1);
                    } else {
                        startForResult(OpenWalletFragment.newInstance(type_register, userInfo, oid_partner, stat_user, name_user, no_idcard, 1), 1);
                    }
                }
                break;
            case R.id.submit_text:
                //重新提交
                if ("5".equals(kyc_status) && !"0".equals(stat_user) && !"1".equals(stat_user)) {
                    startForResult(OpenWalletIDImageFragment.newInstance(type_register, userInfo), 1);
                } else {
                    startForResult(OpenWalletFragment.newInstance(type_register, userInfo, oid_partner, stat_user, name_user, no_idcard, 2), 1);
                }

                break;

        }
    }
}
